package com.bdmc.smokesensor.controller.api;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import com.bdmc.smokesensor.Utils.CommonUtil;
import com.bdmc.smokesensor.Utils.Msg;
import com.bdmc.smokesensor.Utils.ResultUtil;
import com.bdmc.smokesensor.Utils.WebTokenUtil;
import com.bdmc.smokesensor.annotation.AuthIgnore;
import com.bdmc.smokesensor.controller.BaseController;
import com.bdmc.smokesensor.entity.Rbac_Role;
import com.bdmc.smokesensor.entity.Smk_Alarm;
import com.bdmc.smokesensor.entity.Smk_Buildings;
import com.bdmc.smokesensor.entity.Smk_Devices;
import com.bdmc.smokesensor.entity.Smk_GroupCompany;
import com.bdmc.smokesensor.entity.Sys_Log;
import com.bdmc.smokesensor.entity.Sys_User;
import com.bdmc.smokesensor.iservices.IRbac_RoleService;
import com.bdmc.smokesensor.iservices.ISmk_AlarmService;
import com.bdmc.smokesensor.iservices.ISmk_BuildingsService;
import com.bdmc.smokesensor.iservices.ISmk_DevicesService;
import com.bdmc.smokesensor.iservices.ISmk_GroupCompanyService;
import com.bdmc.smokesensor.iservices.ISys_UserService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping(value = "/wechat/admin")
public class AdminController extends BaseController {

    @Autowired
    private ISys_UserService _userSvs;

    @Autowired
    private IRbac_RoleService _roleSvs;

    @Autowired
    private ISmk_DevicesService _devSvs;

    @Autowired
    private ISmk_AlarmService _alarmSvs;

    @Autowired
    private ISmk_BuildingsService _buildSvs;

    @Autowired
    private ISmk_GroupCompanyService _gcSvs;

    @AuthIgnore
    @PostMapping(value = "/bind")
    public Msg bind(@RequestBody Map<String, Object> map) {
        String openid = String.valueOf(map.get("openid"));
        String wxImage = String.valueOf(map.get("wxImage"));
        String wxName = String.valueOf(map.get("wxName"));
        String loginName = String.valueOf(map.get("loginName"));
        String password = String.valueOf(map.get("password"));
        if (StringUtils.isEmpty(loginName) || StringUtils.isEmpty(password)) {
            return ResultUtil.error(-1, "参数错误");
        }
        password = CommonUtil.MD5(password);
        Sys_User u = _userSvs.findByLoginNameAndPassword(loginName, password);
        if (u != null) {
            Rbac_Role role = _roleSvs.findOneById(u.getRbac_RoleId());
            if(!role.getRoleNum().equals("1")&&!role.getRoleNum().equals("3")&&!role.getRoleNum().equals("5")){//验证用户类型
                return ResultUtil.error(-1, "非管理员账户，无法登陆。");
            }
            u.setWxImage(wxImage);
            u.setWxName(wxName);
            u.setOpenid(openid);
            _userSvs.save(u);
            String token = WebTokenUtil.createJWT(u.getId(), u.getOpenid(), u.getDepartmentId(), u.getWxName(),
                    36000000);
            Map<String, Object> respMap = new HashMap<>();
            respMap.put("wxName", wxName);
            respMap.put("wxImage", wxImage);
            respMap.put("openid", openid);
            respMap.put("dep_id", u.getDepartmentId());
            respMap.put("mobile", u.getMobile());
            respMap.put("loginName", u.getLoginName());
            respMap.put("nickName", u.getNickname());
            respMap.put("token", token);
            return ResultUtil.success(respMap);
        } else {
            return ResultUtil.error(-1, "用户不存在。");
        }
    }

    @PostMapping(value = "/unbind")
    public Msg unbind(@RequestBody Map<String, Object> map) {
        int id = Integer.valueOf(request.getAttribute("user_id").toString());
        Sys_User u = _userSvs.findOneById(id);
        if (u != null) {
            u.setWxImage("");
            u.setWxName("");
            u.setOpenid("");
            _userSvs.save(u);
            return ResultUtil.success();
        } else {
            return ResultUtil.error(-1, "用户id不存在");
        }
    }

    // 获取商户信息
    @PostMapping(value = "/shops")
    public Msg getShops(@RequestBody Map<String, Object> map) {
        String name = String.valueOf(map.get("name"));
        int dep_id = Integer.valueOf(request.getAttribute("dep_id").toString());
        Map<String, Object> shops = _buildSvs.findByDepid(name, dep_id);
        return ResultUtil.success(shops);
    }

    // 根据商户id获取设备信息
    @PostMapping(value = "/devices")
    public Msg getDevices(@RequestBody Map<String, Object> map) {
        int id = Integer.valueOf(String.valueOf(map.get("id")));
        List<Smk_Devices> devs = _devSvs.findBySmkBuildingId(id);
        List<Map<Object, Object>> list = new LinkedList<>();
        for (Smk_Devices dev : devs) {
            Map<Object, Object> tempmap = new HashMap<>();
            tempmap.put("imei", dev.getImei());
            tempmap.put("devName", dev.getDevName());
            tempmap.put("devModel", dev.getDevModel());
            tempmap.put("devStatus", dev.getDevStatus());
            tempmap.put("installDate", dev.getInstallDate());
            tempmap.put("installAddr", dev.getInstallAddr());
            list.add(tempmap);
        }
        Map<String,Object> result = new HashMap<>();
        result.put("total", list.size());
        result.put("data", list);
        return ResultUtil.success(result);
    }

    // 根据商户id获取设备报警信息
    @PostMapping(value = "/alarm")
    public Msg getDevicesAlarm(@RequestBody Map<String, Object> map) {
        int id = Integer.valueOf(String.valueOf(map.get("id")));
        List<Map<String, Object>> devs = _alarmSvs.findBySmkBuildingId(id);
        return ResultUtil.success(devs);
    }

    // 根据联网单位和子单位信息
    @PostMapping(value = "/gc_bd")
    public Msg getGroupAndBuildings() {
        int dep_id = Integer.valueOf(request.getAttribute("dep_id").toString());
        List<Map<String, Object>> gcs = _gcSvs.findByDepId(dep_id);
        for (Map<String, Object> m2 : gcs) {
            int gc_id = Integer.valueOf(m2.get("value").toString());
            List<Map<String, Object>> bds = _buildSvs.findByGroupCompanyId(gc_id);
            if (bds != null & bds.size() > 0)
                m2.put("children", bds);
        }
        return ResultUtil.success(gcs);
    }

    // 子单位信息
    @PostMapping(value = "/single_shop")
    public Msg getShopInfo(@RequestBody Map<String, String> map) {
        int id = Integer.valueOf(String.valueOf(map.get("id")));
        Smk_Buildings build = _buildSvs.findOneById(id);
        return ResultUtil.success(build);
    }

    @PostMapping(value = "/save_shop")
    public Msg saveShop(@RequestBody Smk_Buildings bd) {
        String action = bd.getId() > 0 ? "修改:" : "新增:";
        if (!StringUtils.isEmpty(bd.getAreaGcbd())) {
            String arrStr = bd.getAreaGcbd();
            String[] arr = arrStr.split(",");
            Integer gc_id = Integer.valueOf(arr[arr.length - 1]);
            Smk_GroupCompany comp = _gcSvs.findOneById(gc_id);
            bd.setSmkGroupCompanyId(gc_id);
            bd.setDepartmentId(comp.getDepartmentId());
        }
        Smk_Buildings b = _buildSvs.save(bd);
        if (b != null && b.getId() > 0) {
            Sys_Log log = new Sys_Log(getLoginName(), getLocalIp(), "子单位", action + b.getName());
            _logSvs.save(log);
            return ResultUtil.success();
        } else {
            return ResultUtil.error(-1, "操作失败，请联系管理员。");
        }
    }

    @PostMapping(value = "/bind_dev")
    public Msg bindDevice(@RequestBody Map<String, String> map) {
        String dev_imei = String.valueOf(map.get("imei"));
        int build_id = Integer.valueOf(String.valueOf(map.get("bd_id")));
        Smk_Buildings build = _buildSvs.findOneById(build_id);
        Smk_Devices dev = _devSvs.findByImei(dev_imei);
        if(dev==null){
            return ResultUtil.error(-1, "设备不存在。");
        }
        if(dev.getSmkBuildingId()>0){
            return ResultUtil.error(-1, "该设备已被绑定，请勿重复绑定。");
        }
        dev.setDepartmentId(build.getDepartmentId());
        dev.setSmkBuildingId(build_id);
        dev.setAreaGcbd(build.getDepartmentId()+","+build.getSmkGroupCompanyId()+","+build.getId());
        Smk_Devices d = _devSvs.save(dev);
        if (d != null && d.getId() > 0) {
            Sys_Log log = new Sys_Log(getLoginName(), getLocalIp(), "子单位", "绑定设备" + dev.getImei());
            _logSvs.save(log);
            return ResultUtil.success();
        } else {
            return ResultUtil.error(-1, "操作失败，请联系管理员。");
        }
    }

    @PostMapping(value = "/unbind_dev")
    public Msg unbindDev(@RequestBody Map<String, String> map) {
        String dev_imei = String.valueOf(map.get("imei"));
        Smk_Devices dev = _devSvs.findByImei(dev_imei);
        dev.setDepartmentId(1);
        dev.setSmkBuildingId(0);
        Smk_Devices d = _devSvs.save(dev);
        if (d != null && d.getId() > 0) {
            Sys_Log log = new Sys_Log(getLoginName(), getLocalIp(), "子单位", "解除绑定设备" + dev.getImei());
            _logSvs.save(log);
            return ResultUtil.success();
        } else {
            return ResultUtil.error(-1, "操作失败，请联系管理员。");
        }
    }
    @PostMapping(value = "/statistic")
    public Msg statistic() {
        int dep_id = Integer.valueOf(request.getAttribute("dep_id").toString());
        Map<String,Object> results = new HashMap<String,Object>();
        results.put("devStc",_devSvs.findDevTypeSum(dep_id));
        results.put("gcbdStc",_gcSvs.findAreaGCBDSum(dep_id));
        results.put("alarmStc",_alarmSvs.findAlarmSumInfo(dep_id));
        return ResultUtil.success(results);
    }

    // 获取报警信息
    @RequestMapping(value = "/alarmlist")
    public Msg alarmList(@RequestBody Map<String, Object> reqMap) {
        int page = Integer.parseInt(reqMap.get("page").toString());
        int rows = Integer.parseInt(reqMap.get("row").toString());
        int gc_id = 0;
        int alarmType = Integer.parseInt(reqMap.get("alarmType").toString());
        int alarmStat = Integer.parseInt(reqMap.get("alarmStat").toString());
        String start = reqMap.get("start").toString();
        String end = reqMap.get("end").toString();
        int smkBuildingId = Integer.parseInt(reqMap.get("smkBuildingId").toString());

        Map<String, Object> result = _alarmSvs.findByPageable(smkBuildingId, alarmType, alarmStat, start,
                end, gc_id, page, rows);
        return ResultUtil.success(result);
    }

    // 解除报警
    @PostMapping(value = "/relievealarm")
    public Msg relieveAlarm(@RequestBody Map<String, Object> map) {
        Integer id = Integer.valueOf(String.valueOf(map.get("id")));
        Integer dealMethod = Integer.valueOf(String.valueOf(map.get("dealMethod")));
        Integer dealType = Integer.valueOf(String.valueOf(map.get("dealType")));
        String dealResult = String.valueOf(map.get("dealResult"));
        if (id == null || dealMethod == null || dealType == null || dealResult == null) {
            return ResultUtil.error(-1, "参数错误");
        }
        Smk_Alarm alarm = _alarmSvs.findOneById(id);
        alarm.setDealMethod(dealMethod);
        alarm.setDealType(dealType);
        alarm.setDealResult(dealResult);
        alarm.setAlarmStat(2);
        _alarmSvs.save(alarm);
        // HttpResult re = _apiSvs.doGetCommand(alarm.getSmkDevicesId(), "5859");
        return ResultUtil.success();
    }
}